import type { GlobEnvConfig } from '#/config'
import pkg from '../../package.json'
import { API_ADDRESS } from '@/enums/cacheEnum';


export function getCommonStoragePrefix() {
  // PC Template
  const { VITE_GLOB_APP_TITLE } = getAppEnvConfig();
  // 开发模式下 PC_TEMPLATE__DEVELOPMENT
  return `${VITE_GLOB_APP_TITLE.replace(/\s/g, '_')}__${getEnv()}`.toUpperCase();
}

export function getStorageShortName() {
  // 开发模式下 PC_TEMPLATE__DEVELOPMENT__0.0.0__
  return `${getCommonStoragePrefix()}${`__${pkg.version}`}__`.toUpperCase()
}

// 是否为开发模式
export function isDevMode(): boolean {
  return import.meta.env.DEV;
}

// 获取当前模式
export function getEnv(): string {
  return import.meta.env.MODE;
}

// 获取变量名
const getVariableName = (title: string) => {
  function strToHex(str: string) {
    const result: string[] = []
    for (let i = 0; i < str.length; i++) {
      const hex = str.charCodeAt(i).toString(16)
      result.push(('000' + hex).slice(-4))
    }
    return result.join('').toUpperCase()
  }
  // _PRODUCTION__00500043002000540065006D0070006C006100740065__CONF__
  return `__PRODUCTION__${strToHex(title) || '__APP'}__CONF__`.toUpperCase().replace(/\s/g, '')
}

// 获取环境配置
export function getAppEnvConfig() {
  // (.env PC Template) _PRODUCTION__00500043002000540065006D0070006C006100740065__CONF__
  const ENV_NAME = getVariableName(import.meta.env.VITE_GLOB_APP_TITLE)
  const ENV = import.meta.env.DEV
    ? (import.meta.env as unknown as GlobEnvConfig)
    : (window[ENV_NAME] as unknown as GlobEnvConfig)
  const { VITE_GLOB_APP_TITLE, VITE_GLOB_API_URL_PERFIX, VITE_GLOB_UPLOAD_URL } = ENV
  let { VITE_GLOB_API_URL } = ENV
  if (localStorage.getItem(API_ADDRESS)) {
    const address = JSON.parse(localStorage.getItem(API_ADDRESS) || '{}')
    if (address?.key) VITE_GLOB_API_URL = address?.val
  }
  return {
    VITE_GLOB_API_URL_PERFIX,
    VITE_GLOB_API_URL,
    VITE_GLOB_APP_TITLE,
    VITE_GLOB_UPLOAD_URL
  }
}